package com.gpt.article.service.impl.taskHandle.task;

import chatgpt.ChatGPT;
import chatgpt.entity.chat.ChatCompletion;
import chatgpt.entity.chat.ChatCompletionResponse;
import chatgpt.entity.chat.Message;
import com.gpt.article.domain.GptFunPrompts;
import com.gpt.article.domain.GptSpiderArticleTitle;
import com.gpt.article.service.IGptSpiderArticleTitleService;
import com.gpt.article.service.impl.taskHandle.GenTask;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 批量生成内容参数
 */
@Service
public class GenContentTasker {


    private static Logger logger = LoggerFactory.getLogger(GenContentTasker.class);
    private static ChatCompletion chatCompletion;
    private static IGptSpiderArticleTitleService gptSpiderArticleTitleService;
    @Autowired
    public void setIGptSpiderArticleTitleService(IGptSpiderArticleTitleService gptSpiderArticleTitleService) {
        GenContentTasker.gptSpiderArticleTitleService = gptSpiderArticleTitleService;
    }
    /**
     * 每个任务生成50个
     * @param chatGPT
     * @param xigaoTask
     * @param taskId
     * @return
     */
    public boolean genContent(ChatGPT chatGPT, GenTask xigaoTask, Long taskId){
//        WebSocketUsers.sendMessageToUsersByText(getMsgString("source",spiderArticle.getId(),0,"2"));
        Integer oneToNum = xigaoTask.getOneToNum();
        String acc = xigaoTask.getAcc();
        Integer xhNum = 0;
        if(oneToNum<50){
            xhNum = oneToNum ;
        }else{
            xhNum = 50;
        }
        GptFunPrompts gptFunPrompts = xigaoTask.getGptFunPrompts();
        String keyWords = xigaoTask.getKeysWord();
        String refer = xigaoTask.getRefer();
        String prompts = gptFunPrompts.getSystemRole();
//        String prompts = "你的任务是以小红书狗绳子商品标题结构，" +
//                "以我给的主题写一个符合SEO的商品标题，标题内容需具备我给的主题词内容作为包含的参数,参数随机选用80%，以此给我推荐{initNum}篇吸引眼球的个性化" +
//                "商品标题，并且和你以前生成的要求有差别，我给出的主题是：";
//        String pt = prompts.replace("{initNum}",String.valueOf(50));
        Message system = Message.ofSystem(prompts);

        String userPs = "生成数量"+xhNum+"个";
        if(!StringUtils.isEmpty(keyWords)){
            userPs+="，生成的数据必须具备<"+keyWords+">这些参数";
        }
        if(!StringUtils.isEmpty(refer)){
            userPs+="，演示例子："+refer+"。\n" +
                    "和演示例子保持风格一致，并且字数在"+refer.length()+"左右";
        }
        userPs+="。最后希望每一个不要添加排序号并且结尾加上</>便于我分割文本。";

        Message user = Message.of(userPs);
        logger.info("正在执行生成文案任务");
        System.out.println("角色："+prompts);
        System.out.println("用户要求："+userPs);
        chatCompletion = ChatCompletion.builder()
                .model(gptFunPrompts.getUseModel())
                .messages(Arrays.asList(system, user))
                .maxTokens(gptFunPrompts.getMaxTokens())
                .temperature(gptFunPrompts.getTemperature())
                .topP(gptFunPrompts.getTopP())
                .presencePenalty(gptFunPrompts.getPresencePenalty())
                .frequencyPenalty(gptFunPrompts.getFrequencyPenalty())
                .build();
        Message res = null;
//        for(int i=0;i<xhNum;i++){
            ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
            res = response.getChoices().get(0).getMessage();
            String contents = res.getContent();
            String congtent[] = contents.split("</>");
            for(String li:congtent){
                System.out.println("插入title："+li);
                System.out.println("插入keyWords："+keyWords);
                li = getQuchuNo(li);
                insetGenArticleTitle(li,keyWords,acc);
            }

//        }
//        if(y>0){
//            String ypt = prompts.replace("{initNum}",String.valueOf(y));
//             system = Message.ofSystem(ypt);
//             user = Message.of(keyWords);
//            chatCompletion = ChatCompletion.builder()
//                    .model(ChatCompletion.Model.GPT_3_5_TURBO_0613.getName())
////                    .model(ChatCompletion.Model.GPT_3_5_TURBO_16K.getName())
//                    .messages(Arrays.asList(system, user))
//                    .maxTokens(10000)
//                    .temperature(0.9)
//                    .build();
//                ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
//                res = response.getChoices().get(0).getMessage();
//                String title = res.getContent();
//                insetGenArticleTitle(title,keyWords);
//        }


        return true;
    }

    public static void main(String[] args) {
        String str = "【限时特惠】时尚可爱泰迪专用狗绳子，3米长，让你与宠物自由出行！精选高品质材料制作，舒适耐用，不易断裂。轻巧便携，方便收纳。多种颜色可选，时尚潮流。给你的宠物一个舒适又时尚的牵引体验。适合泰迪及其他小型犬。快来选购吧！\n";
        System.out.println(new GenContentTasker().getQuchuNo(str));
    }

    /**
     * 去除开头排序号
     * @param content
     * @return
     */
    public String getQuchuNo(String content){
        content =  content.trim()
                .replace("\r\n","")
        .replace("\n","");
        String outContent = content;
        String regex = "^(\\d+\\.\\s*)+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            outContent = content.substring(matcher.end());
            return outContent;
        }
        return outContent;
    }
    /**
     * 插入数据
     * @param title
     * @return
     */
    public boolean insetGenArticleTitle(String title,String keyWord,String acc){
        GptSpiderArticleTitle spiderArticleTitle = new GptSpiderArticleTitle();
        spiderArticleTitle.setTitle(title);
        String md5str = DateUtils.getNowDate()+"zhu"+title;
        spiderArticleTitle.setUrlMd5(Md5Utils.hash(md5str));
        spiderArticleTitle.setStatus("0");
        spiderArticleTitle.setKeywordPs(keyWord);
        spiderArticleTitle.setCreateBy(acc);
        try{
            gptSpiderArticleTitleService.insertGptSpiderArticleTitle(spiderArticleTitle);
        }catch (Exception e){
            logger.error("error:"+e.getMessage());
        }

        return true;
    }
}
